/*
 * @Description: 公用方法
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2021-01-15 10:18:23
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-03-25 11:25:29
 */
import { DataSet } from 'choerodon-ui/pro/lib';
import { useDataSetEvent } from 'hzero-front/lib/utils/hooks';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';

// 序号公用方法
const renderSort = (record, tableDS) => {
    const { currentPage, pageSize } = tableDS;
    if (!isEmpty(tableDS)) {
      return (record as any).index + 1 + (currentPage - 1) * pageSize;
    } else {
      return (record as any).index + 1;
    }
  };

// 添加按回车查询回调事件
const addEnterCallBack = (tableDS: DataSet, pageRef) =>{

  useEffect(() => {
    const cu: any = pageRef.current;
    const ele = cu.parentNode;

    ele.addEventListener('keydown', handleEventKey);
    return () => {
      ele.removeEventListener('keydown', handleEventKey);
    };
  }, []);

  // 按回车查询事件
  const handleEventKey = e => {
    if (e.keyCode == 13) {
      // 加个settimeout的原因时，解决按回车时查询参数还是上一次的查询条件
      setTimeout(() => {
        tableDS.query();
      }, 10);
    }
  };
}


// 截掉月份后面的时间
const resetMonth = (data,month, type) => {
  let submitData = {};
  if (month) {
      const str = month.substring(0, 7);
      submitData = {
          ...data,
          [type]: str,
      };
  } else {
      submitData = {
          ...data,
      };
  }
  return submitData
}

/**
 * 导出的查询条件hooks
 * @param ds 导出列表dataset
 */
function useQueryParams(ds: DataSet) {
  const [queryObj, setQueryObj] = useState({});
  useDataSetEvent(ds, 'load', () => {
    // 封装导出条件
    let queryData = (ds as any).queryDataSet.toData()[0];
    const queryParameter = ds.queryParameter;
    removeNull(queryData);
    if (queryData.quotaMonth) {
      const str = queryData.quotaMonth.substring(0, 7);
      queryData = {
          ...queryData,
          quotaMonth: str,
      };
  }    
    setQueryObj({ ...queryData, ...queryParameter });
  });
  return queryObj;
}

// 去除对象中值为null的元素
function removeNull(option) {
  if (!option) {
    return;
  }
  for (const attr in option) {
    // eslint-disable-next-line no-prototype-builtins
    if (option.hasOwnProperty(attr)) {
      if (option[attr] === null) {
        // eslint-disable-next-line no-param-reassign
        delete option[attr];
        // eslint-disable-next-line no-continue
        continue;
      }
      if (typeof option[attr] === 'object') {
        removeNull(option[attr]);
      }
    }
  }
}



  export {renderSort, useQueryParams, addEnterCallBack, resetMonth};